<template>
	<div class="content-box add-advertisement">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
			<el-form-item label="广告封面" prop="image">
				<uploadImage v-model:file-list="form.image" :limit="1" :fileSize="300 / 1024">
					<template #tip> 图片格式支持JPG、PNG、GIF,图片尺寸建议宽度800px,高度不限,图片大小不得超过300kb。</template>
				</uploadImage>
			</el-form-item>
			<el-form-item label="广告名称" prop="title">
				<el-input v-model="form.title" placeholder="输入广告名称" />
			</el-form-item>
			<el-form-item label="投放渠道" prop="targetAlipay">
				<el-checkbox v-model="form.targetAlipay" label="支付宝小程序" />
				<el-checkbox v-model="form.targetWx" label="微信小程序" />
			</el-form-item>
			<el-form-item label="投放时间" prop="date">
				<el-date-picker
					v-model="form.date"
					format="YYYY-MM-DD HH:mm"
					date-format="YYYY-MM-DD"
					time-format="HH:mm"
					type="datetimerange"
					:disabled-date="disabledDate"
					start-placeholder="开始时间"
					end-placeholder="结束时间"
					:append-to-body="false"
				/>
			</el-form-item>
			<el-form-item label="广告位置" prop="position">
				<el-radio-group v-model="form.position">
					<el-radio :label="0" size="large">首页轮播</el-radio>
					<el-radio :label="1" size="large">首页图文导航</el-radio>
					<el-radio :label="2" size="large">商城轮播</el-radio>
					<el-radio :label="3" size="large">内容轮播</el-radio>
					<el-radio :label="4" size="large">我的轮播</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="广告排序" prop="orderIdx">
				<el-input-number
					:controls="false"
					class="num-left"
					v-model="form.orderIdx"
					@blur="
						() => {
							form.orderIdx = form.orderIdx || 0;
						}
					"
					:min="0"
					:max="999999999"
					placeholder="输入广告排序"
				/>
			</el-form-item>
			<el-form-item label="落地页方式" prop="type" class="mb40">
				<div>
					<el-radio-group v-model="form.type">
						<el-radio :label="0" size="large">关联商品</el-radio>
						<el-radio :label="1" size="large">关联活动</el-radio>
						<el-radio :label="2" size="large">关联文章</el-radio>
						<el-radio :label="3" size="large">内部路径</el-radio>
						<el-radio :label="4" size="large">外部小程序</el-radio>
						<el-radio :label="5" size="large">仅展示</el-radio>
					</el-radio-group>
					<div v-if="form.type == 0">
						<el-button type="text" @click="openAddGood" class="mb10">+选择商品</el-button>
						<el-table :data="form.product" border>
							<el-table-column label="商品ID" prop="id" width="200" align="center"> </el-table-column>
							<el-table-column label="商品名称" prop="name" align="center">
								<template #default="scope">
									<div class="flex-box">
										<el-image :src="scope.row.imgUrl" style="width: 50px; height: 50px"></el-image>
										<div style="text-align: left; margin-left: 5px">
											<el-tooltip class="box-item" effect="dark" :content="scope.row.name" placement="top">
												<div class="box-name">{{ scope.row.name }}</div>
											</el-tooltip>
											<el-tooltip class="box-item" effect="dark" :content="scope.row.code" placement="top">
												<div class="box-name">编码：{{ scope.row.code }}</div>
											</el-tooltip>
										</div>
									</div>
								</template>
							</el-table-column>
							<el-table-column label="操作" prop="id" width="200" align="center">
								<template #default="scope">
									<el-button type="text" @click="deleteGood(scope, 0)">移除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div v-else-if="form.type == 1">
						<el-button type="text" @click="openAddActivity" class="mb10">+选择活动</el-button>
						<el-table :data="form.product1" border>
							<el-table-column label="活动ID" prop="id" width="200" align="center"> </el-table-column>
							<el-table-column label="活动名称" prop="name" align="center"> </el-table-column>
							<el-table-column label="操作" prop="id" width="200" align="center">
								<template #default="scope">
									<el-button type="text" @click="deleteGood(scope, 1)">移除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div v-else-if="form.type == 2">
						<el-button type="text" @click="openAddContent" class="mb10">+选择文章</el-button>
						<el-table :data="form.product2" border>
							<el-table-column label="文章ID" prop="id" width="200" align="center"> </el-table-column>
							<el-table-column label="文章名称" prop="name" align="center"> </el-table-column>
							<el-table-column label="操作" prop="id" width="200" align="center">
								<template #default="scope">
									<el-button type="text" @click="deleteGood(scope, 2)">移除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div v-else-if="form.type == 3" class="mb10 mt10">
						<el-form-item label="页面路径" label-width="80">
							<el-input v-model="form.product3" placeholder=""></el-input>
						</el-form-item>
					</div>
					<div v-else-if="form.type == 4" class="mb10 mt10">
						<el-form-item label="外部路径" label-width="80">
							<el-input v-model="form.product4" placeholder=""></el-input>
						</el-form-item>
						<el-form-item label="APPID" label-width="80">
							<el-input v-model="form.appId" placeholder=""></el-input>
						</el-form-item>
					</div>
				</div>
			</el-form-item>
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
		<AddItem :visible="updateVisible" @handleClose="handleClose"></AddItem>
		<AddActivity :visible="activeVisible" @handleClose="handleActiveClose"></AddActivity>
		<AddContent :visible="contentVisible" @handleClose="handleContentClose"></AddContent>
	</div>
</template>

<script setup lang="tsx" name="advertisementAdd">
import { computed, inject, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { type FormRules, ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import uploadImage from '/@/components/upload/image.vue';
import { useRoute, useRouter } from 'vue-router';
import { advertisementCreate, advertisementUpdate, advertisementDetail } from '/@/api/advertisement';
import AddItem from '/@/views/pages/activity/list/dialog/addItem.vue';
import AddActivity from './dialog/addActivity.vue';
import AddContent from './dialog/addContent.vue';
import ProTable from '../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../components/ProTable/interface';
const route = useRoute();
const router = useRouter();
const formRef = ref();
const form = ref<any>({
	targetAlipay: false,
	targetWx: false,
	date: [],
	position: 0,
	type: 0,
	product: [],
	product1: [],
	product2: [],
	product3: '',
	product4: '',
});
const editId = ref();
const validateTarget = (rule: any, value: any, callback: any) => {
	if (!form.value.targetAlipay && !form.value.targetWx) {
		callback(new Error('请至少选择一个投放渠道'));
	}
	callback();
};
//校验规则
const rules = reactive<FormRules<any>>({
	image: [{ required: true, trigger: 'blur', message: '广告封面不能为空' }],
	title: [{ required: true, trigger: 'blur', message: '广告名称不能为空' }],
	date: [{ required: true, trigger: 'blur', message: '投放时间不能为空' }],
	position: [{ required: true, trigger: 'blur', message: '广告位置不能为空' }],
	orderIdx: [{ required: true, trigger: 'blur', message: '广告排序不能为空' }],
	type: [{ required: true, trigger: 'blur', message: '请选择落地页方式' }],
	targetAlipay: [{ validator: validateTarget, required: true, trigger: 'blur', message: '请至少选择一个投放渠道' }],
});
const specificationRef = ref();
const updateVisible = ref(false);
const activeVisible = ref(false);
const contentVisible = ref(false);
const openAddGood = () => {
	updateVisible.value = true;
};
const handleClose = (data: any) => {
	updateVisible.value = false;
	if (!form.value.product) {
		form.value.product = [];
		data.forEach((item: any) => {
			form.value.product.push({ ...item, name: item.productName, code: item.productCode, imgUrl: item.productImage });
		});
	} else if (data) {
		data.forEach((item: any) => {
			const has = form.value.product.some((item: any) => item.id == data.id);
			if (!has) {
				form.value.product.push({ ...item, name: item.productName, code: item.productCode, imgUrl: item.productImage });
			}
		});
	}
};
const back = () => {
	router.push('/advertisement/list');
};
const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			if (form.value.type == 0 && (!form.value.product || form.value.product.length == 0)) {
				ElMessage.warning('请选择关联的商品！');
				return;
			} else if (form.value.type == 1 && (!form.value.product1 || form.value.product1.length == 0)) {
				ElMessage.warning('请选择关联的活动！');
				return;
			} else if (form.value.type == 2 && (!form.value.product2 || form.value.product2.length == 0)) {
				ElMessage.warning('请选择关联的文章！');
				return;
			} else if (form.value.type == 3 && !form.value.product3) {
				ElMessage.warning('请输入内部路径！');
				return;
			} else if (form.value.type == 4 && !form.value.appId) {
				ElMessage.warning('请输入外部小程序APPID！');
			} else if (form.value.type == 4 && !form.value.product4) {
				ElMessage.warning('请输入外部小程序路径！');
				return;
			}
			let params = {
				...form.value,
				image: form.value.image[0].url,
				startTime: dayjs(form.value.date[0]).format('YYYY-MM-DD HH:mm'),
				endTime: dayjs(form.value.date[1]).format('YYYY-MM-DD HH:mm'),
			};
			delete params.product;
			delete params.product1;
			delete params.date;
			if (form.value.type == 0) {
				params.bizIdList = form.value.product.map((item: any) => item.id);
			} else if (form.value.type == 1) {
				params.bizIdList = form.value.product1.map((item: any) => item.id);
			} else if (form.value.type == 2) {
				params.bizIdList = form.value.product2.map((item: any) => item.id);
			} else if (form.value.type == 3) {
				params.bizData = form.value.product3;
			} else if (form.value.type == 4) {
				params.bizData = JSON.stringify({
					appId: form.value.appId,
					link: form.value.product4,
				});
			}
			const res = editId.value ? await advertisementUpdate(params) : await advertisementCreate(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑成功' : '新增成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};
function deleteGood(scope: any, type: Number) {
	if (type == 0) {
		form.value.product.splice(scope.$index, 1);
	} else if (type == 1) {
		form.value.product1 = [];
	} else if (type == 2) {
		form.value.product2 = [];
	}
}
const disabledDate = (current: any) => {
	return current && current < dayjs().subtract(1, 'days').endOf('day');
};
const openAddActivity = () => {
	activeVisible.value = true;
};
const handleActiveClose = (data: any) => {
	activeVisible.value = false;
	if (data) {
		form.value.product1 = data;
	}
};
const openAddContent = () => {
	contentVisible.value = true;
};
const handleContentClose = (data: any) => {
	contentVisible.value = false;
	if (data) {
		form.value.product2 = [{ ...data[0], name: data[0].contentTitle }];
	}
};
onMounted(async () => {
	editId.value = route.params.id;
	if (editId.value) {
		const res = await advertisementDetail({ id: editId.value });
		if (res.code === 200) {
			form.value = res.data;
			form.value.image = [{ url: res.data.image }];
			form.value.date = [res.data.startTime, res.data.endTime];
			if (form.value.type == 0) {
				form.value.product = res.data.relBizDataList ? res.data.relBizDataList : [];
			} else if (form.value.type == 1) {
				form.value.product1 = res.data.relBizDataList ? res.data.relBizDataList : [];
			} else if (form.value.type == 2) {
				form.value.product2 = res.data.relBizDataList ? res.data.relBizDataList : [];
			} else if (form.value.type == 3) {
				form.value.product3 = res.data.bizData;
			} else if (form.value.type == 4) {
				const bizData = JSON.parse(res.data.bizData);
				form.value.product4 = bizData.link;
				form.value.appId = bizData.appId;
			}
		}
	}
});
</script>

<style lang="scss" scoped>
.add-advertisement {
	min-height: 800px;

	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number {
			max-width: 450px;
		}
	}

	:deep() .el-table--border th.el-table__cell {
		background: var(--el-fill-color-light);
	}
}

.flex-box {
	display: flex;
}

.box-name {
	width: 147px;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
}
</style>

<style lang="scss">
.add-advertisement {
	.el-form-item {
		.el-input,
		.el-input-number,
		.el-select,
		.el-date-editor,
		.refresh-select-wrapper {
			width: 100%;
			max-width: 450px;
		}
	}
}
</style>
